package org.budo.support.spring.datasource;

import java.util.Map.Entry;

import javax.sql.DataSource;

import org.apache.ibatis.mapping.MappedStatement;
import org.budo.support.ibatis.BudoMybatisInterceptor;
import org.budo.support.spring.util.SpringUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * @author lmw
 */
@Slf4j
public class BudoRoutingDataSource extends AbstractBudoRoutingDataSource {
    private static ThreadLocal<String> ROUTING_DATA_SOURCE_THREAD_LOCAL = new ThreadLocal<String>();

    public static void routing(String dataSource) {
        ROUTING_DATA_SOURCE_THREAD_LOCAL.set(dataSource);
    }

    @Override
    protected DataSource determineTargetDataSource() {
        if (null != ROUTING_DATA_SOURCE_THREAD_LOCAL.get()) {
            return (DataSource) SpringUtil.getBeanCached(ROUTING_DATA_SOURCE_THREAD_LOCAL.get()); // dataSource-oracle //
        }

        MappedStatement threadLocalMappedStatement = BudoMybatisInterceptor.getThreadLocalMappedStatement();
        if (null == threadLocalMappedStatement) {
            log.debug("#32 threadLocalMappedStatement is null, using dataSource-mysql, this={}", this);

            return (DataSource) SpringUtil.getBeanCached(this.getDefaultDataSource()); // dataSource-oracle //
        }

        String statementId = threadLocalMappedStatement.getId();
        for (Entry<String, Object> entry : this.getDataSourceMap().entrySet()) {
            if (statementId.startsWith(entry.getValue() + "")) {
                return (DataSource) SpringUtil.getBeanCached(entry.getKey()); // dataSource-oracle // dataSource-mysql
            }
        }

        return (DataSource) SpringUtil.getBeanCached(this.getDefaultDataSource()); // dataSource-oracle // dataSource-mysql
    }
}